package com.example.financeapi.controller;

import com.example.financeapi.entity.FSecuritiesAccount;
import com.example.financeapi.entity.FSecuritiesCompany;
import com.example.financeapi.enums.ResultEnum;
import com.example.financeapi.service.FSecuritiesAccountService;
import com.example.financeapi.entity.vo.ResultVOUtil;
import com.example.financeapi.entity.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 证券账户表(FSecuritiesAccount)表控制层
 * @author Alvin
 */
@Slf4j
@RestController
@RequestMapping("fSecuritiesAccount")
public class FSecuritiesAccountController {

    @Autowired
    private StringEncryptor stringEncryptor;

    @Autowired
    private FSecuritiesAccountService fSecuritiesAccountService;

    /**
     * 获取账号列表
     * @param request
     * @return
     */
    @GetMapping("getAccountList")
    public ResultVo getAccountList(HttpServletRequest request) {
        String getUnionid = request.getServletContext().getAttribute("unionid")+"";
        Map<String,Object> paramMap =new HashMap<>();
        if(StringUtils.isBlank(getUnionid)){
            log.error("【接口：getAccountList】没有数据，uinonid={}" + getUnionid);
            return ResultVOUtil.error("【uinonid=" + getUnionid + "】" + ResultEnum.PARAM_IS_NULL.getMessage());
        }
        paramMap.put("unionid",getUnionid);
        List<FSecuritiesAccount> getAccountList=fSecuritiesAccountService.getAccountList(paramMap);
        return ResultVOUtil.success(getAccountList);
    }

    /**
     * 获取单个账号信息
     * @param id 证券账号
     * @return
     */
    @GetMapping("queryById")
    public ResultVo queryById(@RequestParam String id) {
        if(StringUtils.isBlank(id)){
            log.error("【接口：queryById】没有数据，id={}" + id);
            return ResultVOUtil.error("【id=" + id + "】" + ResultEnum.PARAM_IS_NULL.getMessage());
        }
        FSecuritiesAccount securitiesAccount = fSecuritiesAccountService.queryById(id);
        if(securitiesAccount !=null){
            String getSignalPassword =stringEncryptor.decrypt(securitiesAccount.getSignalPassword());
            String getTraderPassword =stringEncryptor.decrypt(securitiesAccount.getTraderPassword());
            securitiesAccount.setSignalPassword(getSignalPassword);
            securitiesAccount.setTraderPassword(getTraderPassword);
        }
        return ResultVOUtil.success(securitiesAccount);
    }

    /**
     * 添加账号信息
     * @param securitiesAccount
     * @param bindingResult
     * @param request
     * @return
     */
    @PostMapping("addAccount")
    public ResultVo addAccount(@Valid @RequestBody FSecuritiesAccount securitiesAccount, BindingResult bindingResult, HttpServletRequest request) {
        String getUnionid = request.getServletContext().getAttribute("unionid")+"";
        int result =0;
        try {
            if (bindingResult.hasErrors()) {
                log.error("【获取账号列表】参数不正确，securitiesAccount={},getUnionid={}",securitiesAccount,getUnionid);
                return ResultVOUtil.error(bindingResult.getFieldError().getDefaultMessage());
            }
            if (Objects.isNull(securitiesAccount)) {
                return ResultVOUtil.error(ResultEnum.PARAM_IS_NULL.getMessage());
            }
            securitiesAccount.setUnionid(getUnionid);
            String getTraderPassword =stringEncryptor.encrypt(securitiesAccount.getTraderPassword());
            String getSignalPassword =stringEncryptor.encrypt(securitiesAccount.getSignalPassword());
            securitiesAccount.setSignalPassword(getSignalPassword);
            securitiesAccount.setTraderPassword(getTraderPassword);
            result =fSecuritiesAccountService.insert(securitiesAccount);
            if(result==0){
                return ResultVOUtil.error("该客户号【"+securitiesAccount.getCustomeCode()+"】已存在！"+ ResultEnum.INSERT_DATA_ERROR.getMessage());
            }
        } catch (Exception e) {
            log.error("【接口：addAccount】后台异常msg={}，securitiesAccount={},getUnionid={},e={}",e.getMessage(), securitiesAccount,getUnionid,e);
            return ResultVOUtil.error(ResultEnum.PROGRAM_EXCEPTION.getMessage() + e.getMessage(), e);
        }
        return ResultVOUtil.success("添加"+ResultEnum.SUCCESS.getMessage());
    }

    /**
     * 修改账号信息
     * @param securitiesAccount
     * @param bindingResult
     * @param request
     * @return
     */
    @PostMapping("updateAccount")
    public ResultVo updateAccount(@Valid @RequestBody FSecuritiesAccount securitiesAccount, BindingResult bindingResult, HttpServletRequest request) {
        Map<String,Object> paramMap =new HashMap<>();
        String getUnionid = request.getServletContext().getAttribute("unionid")+"";
        try {
            if (bindingResult.hasErrors()) {
                log.error("【修改账号信息】参数不正确，securitiesAccount={},getUnionid={}",securitiesAccount,getUnionid);
                return ResultVOUtil.error(bindingResult.getFieldError().getDefaultMessage());
            }
            if (Objects.isNull(securitiesAccount)) {
                return ResultVOUtil.error(ResultEnum.PARAM_IS_NULL.getMessage());
            }
            if (StringUtils.isBlank(securitiesAccount.getId()+"")) {
                return ResultVOUtil.error("id "+ResultEnum.PARAM_IS_NULL.getMessage());
            }
            FSecuritiesAccount account =fSecuritiesAccountService.queryById(securitiesAccount.getId()+"");
            if(account==null){
                log.error("【修改账号信息】参数不正确，securitiesAccount={},getUnionid={}",securitiesAccount,getUnionid);
                return ResultVOUtil.error("id=【"+securitiesAccount.getId()+"】"+ResultEnum.DATA_NOT_EXIST.getMessage());
            }
            paramMap.put("ascriptionPlatform",securitiesAccount.getAscriptionPlatform().trim());
            paramMap.put("customeCode",securitiesAccount.getCustomeCode().trim());
            List<FSecuritiesAccount> accountTwo =fSecuritiesAccountService.getAccountList(paramMap);
            if(!CollectionUtils.isEmpty(accountTwo)){
                if(accountTwo.size() >1){
                    return ResultVOUtil.error("客户号已存在！");
                }else if(accountTwo.size() ==1){
                    if(account.getCustomeCode().equals(securitiesAccount.getCustomeCode())){
                        securitiesAccount.setCustomeCode("");
                    }else{
                        return ResultVOUtil.error("客户号已存在！");
                    }
                }
            }
            securitiesAccount.setUnionid(getUnionid);
            String getTraderPassword =stringEncryptor.encrypt(securitiesAccount.getTraderPassword());
            String getSignalPassword =stringEncryptor.encrypt(securitiesAccount.getSignalPassword());
            securitiesAccount.setSignalPassword(getSignalPassword);
            securitiesAccount.setTraderPassword(getTraderPassword);
            int result =fSecuritiesAccountService.update(securitiesAccount);
            if(result>0){
                return ResultVOUtil.success("修改"+ResultEnum.SUCCESS.getMessage());
            }else{
                return ResultVOUtil.error(ResultEnum.UPDATE_FAIL.getMessage());
            }

        } catch (Exception e) {
            log.error("【接口：updateAccount】后台异常msg={}，securitiesAccount={},getUnionid={},e={}",e.getMessage(), securitiesAccount,getUnionid,e);
            return ResultVOUtil.error(ResultEnum.PROGRAM_EXCEPTION.getMessage() + e.getMessage(), e);
        }
    }

    /**
     * 获取证券列表
     * @param paramMap
     * @return
     */
    @GetMapping("getSecuritiesCompanyList")
    public ResultVo getSecuritiesCompanyList(Map<String,Object> paramMap) {
        List<FSecuritiesCompany> FSecuritiesCompany = fSecuritiesAccountService.getSecuritiesCompanyList(paramMap);
        return ResultVOUtil.success(FSecuritiesCompany);
    }

    /**
     * 删除证券
     * @param id
     * @return
     */
    @GetMapping("deleteById")
    public ResultVo deleteById(String id) {
        int result =fSecuritiesAccountService.deleteById(id);
        return ResultVOUtil.success(result);
    }

}